package com.kgar.util;

import cn.hutool.http.HttpException;
import cn.hutool.json.JSONUtil;
import okhttp3.*;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.util.CastUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@Component
@Lazy
public class TextExtractor {
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Value("${baiduai.text.access_token}")
    private String access_token;

    public String parse2Text(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // pdf_file 可以通过 getFileContentAsBase64("C:\fakepath\服务外包承诺书.pdf") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        String fileContentAsBase64 = getFileContentAsBase64(path, true);
        return creatRequest(mediaType, fileContentAsBase64);
    }

    @Nullable
    private String creatRequest(MediaType mediaType, String fileContentAsBase64) {
        RequestBody body = RequestBody.create("pdf_file="+fileContentAsBase64, mediaType);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + access_token)
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            String sb = parseResult(response);
            if (sb != null) return sb;
        } catch (Exception e) {
            throw new HttpException("api接口请求失败！");
        }
        return null;
    }

    @Nullable
    private static String parseResult(Response response) throws IOException {
        if (response.body() != null) {
            //解析响应结果
            String result = response.body().string();
            Map<String,Object> map = JSONUtil.parseObj(result);
            if(map.containsKey("error_msg")){
                throw new HttpException(map.get("error_msg").toString());
            }
            List<Map<String,String>> list= CastUtils.cast( map.get("words_result"));
            //将每行结果 拼接为字符串
            StringBuilder sb = new StringBuilder();
            list.forEach(listmap->{
                String row = listmap.get("words");
                sb.append(row);
                sb.append("\n");
            });

            return sb.toString();
        }
        return null;
    }

    public String parse2Text(MultipartFile file) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        String fileContentAsBase64 = getFileContentAsBase64(file.getBytes(), true);
        return creatRequest(mediaType, fileContentAsBase64);
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        return getFileContentAsBase64(b, urlEncode);
    }

    private static String getFileContentAsBase64(byte[] b, boolean urlEncode) {
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, StandardCharsets.UTF_8);
        }
        return base64;
    }


}
